package com.coder._02.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimeServerPOJO {

    private int port;

    public TimeServerPOJO(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();    // 用来接收连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();  // 用来处理接收到的连接
        System.out.println(String.format("准备运行的端口：%s", port));

        try {
            ServerBootstrap b = new ServerBootstrap(); // 启动NIO服务的辅助类
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // channel如何接收新的连接
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 自定义处理类
                            // 注意添加顺序
                            ch.pipeline().addLast(new TimeEncoderPOJO(), new TimeServerHandlerPOJO());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = b.bind(port).sync();

            future.channel().closeFuture().sync();

        } catch (Exception e) {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new TimeServerPOJO(8080).run();
    }

}
